<template>
  <el-card style="padding: 20px">
    <el-form ref="formRef" :model="form" inline>
      <el-form-item
        v-for="(
          {
            form_item_json: { label, prop },
            component_name,
            component_json,
            component_handle,
          },
          index
        ) in form_json"
        :key="index"
        v-bind="{ label, prop }"
      >
        <component
          :is="component_name"
          v-model="form[prop]"
          v-bind="component_json"
          v-on="component_handle"
        >
          <template v-if="component_name === 'el-select'">
            <el-option
              v-for="(i, v) in component_json.option_data"
              :key="v"
              v-bind="i"
            ></el-option>
          </template>
        </component>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="get_list"
          >搜索</el-button
        >
        <el-button size="mini" icon="el-icon-refresh" @click="reset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="function" style="margin-bottom: 20px">
      <el-button
        @click="handle_add"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        plain
        >新增</el-button
      >
      <el-button
        :disabled="ids.length !== 1"
        size="mini"
        type="success"
        icon="el-icon-edit"
        plain
        @click="handle_edit(ids[0])"
        >修改</el-button
      >

      <el-button
        :disabled="!ids.length"
        size="mini"
        type="danger"
        icon="el-icon-delete"
        plain
        @click="handle_del(ids)"
        >删除</el-button
      >
      <el-button
        disabled
        size="mini"
        type="warning"
        icon="el-icon-download"
        plain
        >导出</el-button
      >
    </div>
    <el-table :data="list" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column v-slot="scope" label="图片">
        <el-image
          style="height: 60px; width: 60px"
          :src="getUrl(scope.row.img)"
        ></el-image>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in list_json"
        :key="index"
        v-bind="item"
      >
        <template v-if="item.prop === 'status'" v-slot="scope">
          <el-switch
            @change="change(scope.row)"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-slot="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handle_edit(scope.row.id)"
          >修改</el-button
        >
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          @click="handle_del(scope.row.id)"
          >删除</el-button
        >
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: right; margin-top: 20px"
      background
      @size-change="
        (val) => {
          this.pager.pageSize = val;
          this.get_list();
        }
      "
      @current-change="
        (val) => {
          this.pager.pageNum = val;
          this.get_list();
        }
      "
      :current-page="pager.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pager.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pager.totalRow"
    >
    </el-pagination>
    <el-dialog
      :title="title"
      :visible="visible"
      width="35%"
      @close="close"
      @closed="llq"
    >
      <el-form
        ref="formEditRef"
        :model="form_edit"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="菜系" prop="cuisineId">
          <el-select v-model="form_edit.cuisineId" placeholder="菜系">
            <el-option
              v-for="item in cuisine_list"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="(
            { form_item_json: { label, prop }, component_name, component_json },
            index
          ) in form_edit_json"
          :key="index"
          v-bind="{ label, prop }"
        >
          <component
            :is="component_name"
            v-model="form_edit[prop]"
            v-bind="component_json"
          >
            <template v-if="component_name === 'el-select'">
              <el-option
                v-for="(i, v) in component_json.option_data"
                :key="v"
                v-bind="i"
              ></el-option>
            </template>
          </component>
        </el-form-item>
        <el-form-item label="菜品图片">
          <el-upload
            :headers="uploadHeaders"
            action="http://8.138.102.145/api/upload/dish"
            list-type="picture-card"
            :limit="1"
            :file-list="file_list"
            :on-success="handle_success"
            :on-exceed="on_exceed"
            accept="jpg,png,jpeg"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-divider>菜品详情列表</el-divider>
      <el-button
        @click="handle_add_itemlist"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        plain
        >新增</el-button
      >
      <el-button
        :disabled="!ids_itemlist.length"
        size="mini"
        type="danger"
        icon="el-icon-delete"
        plain
        @click="handle_del_itemlist"
        >删除</el-button
      >
      <el-table
        style="margin-top: 20px"
        :data="itemlist"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column align="center" label="口味" prop="name" v-slot="scope">
          {{ scope.row.name }}
          <el-button
            type="text"
            @click="
              open = true;
              index = scope.$index;
            "
            >选择口味</el-button
          >
        </el-table-column>
        <el-table-column
          align="center"
          label="单价"
          prop="price"
        ></el-table-column>
        <el-table-column
          align="center"
          label="状态"
          prop="status"
          v-slot="scope"
        >
          <el-switch
            disabled
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button type="primary" size="mini" @click="submit">确定</el-button>
          <el-button size="mini" @click="visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <tasteDialog :open="open" @close="open = false" @fun="fun" />
  </el-card>
</template>

<script>
import { omit } from "lodash";
import taste from "./taste.vue";
import tasteDialog from "./tasteDialog.vue";
export default {
  mounted() {
    this.get_list();
    this.get_list_cuisine();
    const token = sessionStorage.getItem("token");
    if (token) {
      this.uploadHeaders.Authorization = `${token}`;
    }
  },
  components: {
    taste,
    tasteDialog,
  },
  data() {
    return {
      ids: [],
      pager: {
        pageNum: 1,
        pageSize: 10,
        totalRow: 0,
      },
      list: [],
      list_json: [
        { label: "菜品", prop: "name" },
        { label: "单价", prop: "price" },
        { label: "状态", prop: "status" },
      ],
      form: {
        name: "",
        status: "",
      },
      form_json: [
        {
          form_item_json: { label: "菜品", prop: "name" },
          component_name: "el-input",
          component_json: { placeholder: "菜品", size: "small" },
        },
        {
          form_item_json: { label: "状态", prop: "status" },
          component_name: "el-select",
          component_json: {
            placeholder: "状态",
            size: "small",
            option_data: [
              { label: "启用", value: 1 },
              { label: "禁用", value: 0 },
            ],
          },
          component_handle: {
            change: this.myChange,
          },
        },
        {
          form_item_json: { label: "菜系", prop: "cuisineId" },
          component_name: "el-select",
          component_json: {
            placeholder: "菜系",
            size: "small",
            option_data: [],
          },
          component_handle: {
            change: this.myChange,
          },
        },
      ],
      form_edit: {
        name: "",
        price: "",
        status: "",
        cuisineId: "",
        img: "",
        describe:"",
        type:0,
        sort: 100,
      },
      form_edit_json: [
        {
          form_item_json: { label: "菜品", prop: "name" },
          component_name: "el-input",
          component_json: { placeholder: "菜品", size: "small" },
        },
        {
          form_item_json: { label: "单价", prop: "price" },
          component_name: "el-input",
          component_json: {
            placeholder: "单价",
            size: "small",
            type: "number",
            min: 0,
          },
        },
        {
          form_item_json: { label: "状态", prop: "status" },
          component_name: "el-select",
          component_json: {
            placeholder: "状态",
            size: "small",
            option_data: [
              { label: "启用", value: 1 },
              { label: "禁用", value: 0 },
            ],
          },
        },
        {
          form_item_json: { label: "类型", prop: "type" },
          component_name: "el-select",
          component_json: {
            placeholder: "请选择类型",
            size: "small",
            option_data: [
              { label: "默认", value: 0 },
              { label: "新品推荐", value: 1 },
              { label: "销量霸榜", value: 2 },
              { label: "用户好评", value: 3 },
            ],
          },
        },
        {
          form_item_json: { label: "排序", prop: "sort" },
          component_name: "el-input-number",
          component_json: {
            placeholder:"值越小 越靠前",
            size: "small",
            max: 100,
            min: 0,
          },
        },
        {
          form_item_json: { label: "描述", prop: "describe" },
          component_name: "el-input",
          component_json: {
            placeholder: "请填写描述",
            size: "small",
            type: "textarea",
            rows: 3,
            resize: "none",
          },
        },
      ],
      title: "",
      visible: false,
      rules: {
        name: [{ required: true, message: "请输入菜品", trigger: "blur" }],
      },
      is_add: false,
      itemlist: [],
      itemlist_json: [
        { label: "口味", prop: "name" },
        { label: "单价", prop: "price" },
        { label: "状态", prop: "status" },
      ],
      ids_itemlist: [],
      open: false,
      index: 0,
      del_ids: [],
      cuisine_list: [],
      uploadHeaders: {},
      file_list: [],
    };
  },
  methods: {
    myChange() {
      this.pager.pageNum = 1;
      console.log(this.pager.pageNum);
    },
    getUrl(img) {
      return "http://8.138.102.145:8232/images/" + img;
    },
    get_list() {
      this.$http
        .get("/dish", {
          params: {
            ...this.pager,
            ...this.form,
          },
        })
        .then((res) => {
          this.list = res.rows;
          this.pager = omit(res, ["msg", "status", "rows"]);
        });
    },
    get_list_cuisine() {
      this.$http
        .get("/cuisine", {
          params: {
            pgaeSize: 999,
          },
        })
        .then((res) => {
          this.cuisine_list = res.rows;
          this.form_json[2].component_json.option_data = res.rows.map((v) => {
            return {
              value: v.id,
              label: v.name,
            };
          });
        });
    },
    reset() {
      this.$refs.formRef.resetFields();
      this.pager.pageNum = 1;
      this.pager.pageSize = 10;
      this.get_list();
    },
    handleSelectionChange(val) {
      this.ids = val.map((v) => v.id);
    },
    handle_add() {
      this.visible = true;
      this.title = "添加菜品";
      this.is_add = true;
    },
    handle_del_itemlist() {
      this.itemlist = this.itemlist.filter(
        (v) => !this.ids_itemlist.includes(v.id)
      );
    },
    handle_add_itemlist() {
      this.itemlist.push({
        id: Math.floor(Math.random() * 10000),
        name: "",
        price: 0,
        status: 1,
      });
      console.log(this.itemlist);
    },
    handle_edit(id) {
      this.visible = true;
      this.title = "修改菜品";
      this.is_add = false;
      this.file_list = [
        {
          url:
            "http://8.138.102.145:8232/images/" +
            this.list.find((v) => v.id == id).img,
        },
      ];
      Object.assign(
        this.form_edit,
        this.list.find((v) => v.id == id)
      );
      this.itemlist = this.list.find((v) => v.id == id).itemList;
      console.log(this.itemlist);
    },
    handle_del(id) {
      this.$confirm("是否确认删除菜品?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`/dish${this.getIds(id)}`).then((res) => {
            if (res.status === 200) {
              this.$message.success(res.msg);
              this.get_list();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    submit() {
      this.$refs.formEditRef.validate((callback) => {
        console.log(this.form_edit);
        if (callback) {
          if (this.is_add) {
            this.$http
              .post("/dish", { ...this.form_edit, itemList: this.itemlist })
              .then((res) => {
                if (res.status === 200) {
                  this.$message.success(res.msg);
                  this.visible = false;
                  this.get_list();
                }
              });
          } else {
            this.$http
              .put("/dish", { ...this.form_edit, itemList: this.itemlist })
              .then((res) => {
                if (res.status === 200) {
                  this.$message.success(res.msg);
                  this.visible = false;
                  this.get_list();
                }
              });
          }
        }
      });
    },
    close() {
      this.$refs.formEditRef.resetFields();
      this.form_edit = {
        name: "",
        price: "",
        status: "",
        cuisineId: "",
        img: "",
      };
      this.itemlist = [];
      this.visible = false;
    },
    fun(row) {
      this.itemlist.splice(this.index, 1, row);
      console.log(this.index);
    },
    change(val) {
      this.$http.put("/dish", val);
    },
    llq() {
      this.file_list = [];
    },
    // get_itemlist(id) {
    //   this.$http.get(`/dishItem?id=${id}`).then((res) => {
    //     this.itemList = res.data.itemList;
    //     this.visible2=true
    //   });
    // },
    selectionChange(row) {
      this.ids_itemlist = row.map((v) => v.id);
      console.log(this.ids_itemlist);
    },
    getType() {
      let arr = ["", "success", "info", "danger", "warning"];
      return arr[Math.floor(Math.random() * arr.length)];
    },
    handle_success(file) {
      this.form_edit.img = file.data;
    },
    on_exceed() {
      this.$message.warning("只能上传一张图片");
    },
    getIds(ids) {
      if (Array.isArray(ids)) {
        if (ids.length > 0) {
          const params = new URLSearchParams();
          ids.forEach((id) => {
            params.append("id", id);
          });
          ids = params.toString();
        } else {
          ids = "";
        }
        return `?${ids}`;
      } else {
        return `?id=${ids}`;
      }
    },
  },
};
</script>

<style style="scss">
.el-table__header th {
  background-color: #f8f8f9 !important;
  color: #515a6e;
}
</style>
